import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:largefriends/pages/lf_feedback/lf_feedback_logic.dart';
import 'package:largefriends/pages/lf_verify/lf_verify_camera/lf_verify_camera_logic.dart';
import 'package:largefriends/res.dart';
import 'package:largefriends/res/lf_color.dart';
import 'package:largefriends/res/lf_double_ext.dart';
import 'package:largefriends/res/strings/lf_strings.dart';
import 'package:largefriends/widgets/custom_cache_image.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../res/lf_fonts.dart';
import '../../../res/lf_text_style.dart';
import '../../../widgets/lf_button.dart';

class LfVerifyCameraPage extends StatefulWidget {
  const LfVerifyCameraPage({super.key});

  @override
  State<LfVerifyCameraPage> createState() => _LfVerifyCameraPageState();
}

class _LfVerifyCameraPageState extends State<LfVerifyCameraPage>
    with WidgetsBindingObserver, TickerProviderStateMixin {
  final logic = Get.put(LfVerifyCameraLogic());

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (logic.cameraController == null) {
      return;
    }
    // App state changed before we got the chance to initialize.
    if (!logic.cameraController!.value.isInitialized) {
      return;
    }

    if (state == AppLifecycleState.inactive) {
      logic.cameraController!.dispose();
    } else if (state == AppLifecycleState.resumed) {
      logic.initCamera();
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          backgroundColor: color210215,
          appBar: AppBar(
            backgroundColor: Colors.transparent,
            leading: InkWell(
              child: Image.asset(Res.common_back_button),
              onTap: () {
                Get.back();
              },
            ),
          ),
          extendBodyBehindAppBar: true,
          body: GetBuilder<LfVerifyCameraLogic>(
            builder: (logic) {
              if (logic.loadState == 0) {
                return Container();
              } else if (logic.loadState == 1) {
                return Stack(
                  children: [
                    CameraPreview(logic.cameraController!),
                    Align(
                      alignment: Alignment.bottomCenter,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        mainAxisAlignment: MainAxisAlignment.end,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Obx(() => Visibility(
                              visible: logic.isRecording.isFalse,
                              child: Padding(
                                padding: EdgeInsets.symmetric(horizontal: 10.w),
                                child: Text(
                                  strImportantTipsForQuickVerification.tr,
                                  style: lfTextStyle(
                                    sp: 14.sp,
                                    fontFamily: fontMedium,
                                  ),
                                ),
                              ))),
                          6.h.sbh,
                          Obx(() => Visibility(
                              visible: logic.isRecording.isFalse,
                              child: Padding(
                                  padding:
                                      EdgeInsets.symmetric(horizontal: 10.w),
                                  child: Row(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: [
                                      Text("·",
                                          style: lfTextStyle(
                                            sp: 14.sp,
                                            fontFamily: fontBold,
                                          )),
                                      6.w.sbw,
                                      Expanded(
                                          child: Text(
                                              strMakeSureFaceVisiableTip.tr,
                                              style: lfTextStyle(
                                                sp: 14.sp,
                                                fontFamily: fontRegular,
                                              )))
                                    ],
                                  )))),
                          6.h.sbh,
                          Obx(() => Visibility(
                                visible: logic.isRecording.isFalse,
                                child: Padding(
                                    padding:
                                        EdgeInsets.symmetric(horizontal: 10.w),
                                    child: Row(
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text("·",
                                            style: lfTextStyle(
                                              sp: 14.sp,
                                              fontFamily: fontBold,
                                            )),
                                        6.w.sbw,
                                        Expanded(
                                            child:
                                                Text(strCopyGestureLongTip.tr,
                                                    style: lfTextStyle(
                                                      sp: 14.sp,
                                                      fontFamily: fontRegular,
                                                    )))
                                      ],
                                    )),
                              )),
                          40.h.sbh,
                          Center(
                            child: InkWell(
                              child: SizedBox(
                                width: 66.r,
                                height: 66.r,
                                child: Obx(() {
                                  return Stack(
                                    children: [
                                      Positioned.fill(
                                          child: CircularProgressIndicator(
                                        backgroundColor: Colors.white,
                                        strokeWidth: 6.r,
                                        valueColor:
                                            AlwaysStoppedAnimation(colorFF007F),
                                        value: logic.duration.value / 8000,
                                      )),
                                      Center(
                                          child: logic.isRecording.isTrue
                                              ? Container(
                                                  width: 33.r,
                                                  height: 33.r,
                                                  decoration: BoxDecoration(
                                                      color: colorFF007F,
                                                      borderRadius:
                                                          10.r.radius),
                                                )
                                              : Container(
                                                  width: 46.r,
                                                  height: 46.r,
                                                  decoration:
                                                      const BoxDecoration(
                                                          shape:
                                                              BoxShape.circle,
                                                          color: Colors.white),
                                                )),
                                    ],
                                  );
                                }),
                              ),
                              onTap: () {
                                if (logic.isRecording.isTrue) {
                                  logic.endRecord();
                                } else {
                                  logic.startRecord();
                                }
                              },
                            ),
                          ),
                          10.h.sbh,
                          Center(
                            child: Obx(() {
                              var tip = logic.duration.value ~/ 1000;
                              return Opacity(
                                opacity: logic.isRecording.isTrue ? 1 : 0,
                                child: Text(
                                  '00:0$tip',
                                  style: lfTextStyle(
                                      sp: 14.sp,
                                      fontFamily: fontMedium,),
                                ),
                              );
                            }),
                          ),
                          30.h.sbh,
                        ],
                      ),
                    ),
                    Positioned(
                      left: 10.w,
                      top: 80.h,
                      child: CustomCacheImage(
                        imageUrl: logic.gestureEntity.pic,
                        width: 140.w,
                        radius: 10.r,
                      ),
                    )
                  ],
                );
              } else {
                return Container(
                  color: color50F2A7BE,
                  alignment: Alignment.center,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: errorTips(),
                  ),
                );
              }
            },
          ),
        ),
        onWillPop: () async {
          Get.back();
          return false;
        });
  }

  List<Widget> errorTips() {
    List<Widget> items = List.empty(growable: true);
    var tips = "";
    var actionTip = "";
    if (logic.errorTips == 'CameraAccessDenied') {
      tips = strAccessToCameraTip.tr;
      actionTip = strAccessCamera.tr;
    } else if (logic.errorTips == 'AudioAccessDenied') {
      tips = strAccessMicrophone.tr;
      actionTip = strAccessMicrophone.tr;
    } else {
      tips = strSomethingWrong.tr;
      actionTip = strContactUs.tr;
    }
    items.add(Padding(
      padding: EdgeInsets.symmetric(
        horizontal: 20.w,
      ),
      child: Text(
        tips,
        textAlign: TextAlign.center,
        style: lfTextStyle(sp: 17.sp, fontFamily: fontMedium),
      ),
    ));
    items.add(30.h.sbh);
    items.add(Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: LfButton(
        text: strContinue.tr,
        onPress: () {
          if (actionTip == strContactUs.tr) {
            toFeedback(type: FeedbackType.account);
          } else {
            openAppSettings();
          }
        },
        enabled: true,
      ),
    ));
    return items;
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }
}
